<?php
include("./config/session-action.php");
include("./config/config.inc.php");

/*上传文件操作*/
class CUserQQUpload extends JsonBase
{
	private $mysqli	= null;
	private $file		= null;
	/* 构造函数 */
	function OnPageLoad() {
		global $mysql_server, $mysql_user, $mysql_passwd, $mysql_database;
		
		// 上传文件 
		if(  !isset($_FILES["file"]) ){
			$this->json["msg"] = "上传文件失败";
			return;
		}
		// 连接数据库
		$server = explode(":", $mysql_server, 2);
		$this->mysqli = new mysqli($server[0], $mysql_user, $mysql_passwd, $mysql_database, isset($server[1])?$server[1]:3306);
		if( mysqli_connect_errno() ){
			$this->json["msg"] = "连接数据库失败";
			$this->mysqli = null;
			return;
		}
		$this->mysqli->autocommit(FALSE);
		// 打开文件
		$this->file = fopen($_FILES["file"]["tmp_name"], "r");
		if( !$this->file ){
			$this->json["msg"] = "读取文件失败";
			return;
		}
		$count = 0;
		// 分析文件, 格式：[QQ号码]\t[QQ昵称]\t[绿网账号]\t[生成时间(年-月-日 是:分:秒)]\t[是否购买服务(0未购买,1已购买)]
		while( $row = fscanf($this->file, "%s\t%s\t%s\t%s\t%s\r\n") ){
			foreach( $row as $key => $value ){
				if($value == '""')
					$row[$key] = "";
			}
			$qq = str_replace("'", "''", $row[0]);
			$name = str_replace("'", "''", $row[1]);
			$gwlogin = str_replace("'", "''", $row[2]);
			$getdt = ( "" == $row[3] )?date("Y-m-d H:i:s"):str_replace("'", "''", $row[3]);
			$gwbuy = (int)$row[4];
			$sql = "insert into t_user_qq2(qq,name,license,fistdt,active,email) values('{$qq}','{$name}','{$gwlogin}','{$getdt}', {$gwbuy}, '{$qq}@qq.com')";
			if( !$this->mysqli->query($sql) ){
				//$this->json["msg"] = "添加行\"{$row[0]} {$row[1]} {$row[2]} {$row[3]} {$row[4]}\"失败";
				//return;
				continue;
			}
			$count ++;
		}
		$this->json["success"] = true;
		$this->json["msg"] = "导入记录{$count}条";
	}
	/* 析构函数 */
	function __destruct() {
		// 关闭MYSQL
		if( $this->mysqli ){
			if(true == $this->json["success"])
				$this->mysqli->commit();
			else
				$this->mysqli->rollback();
			$this->mysqli->close();
		}
		// 关闭文件
		if( $this->file ){
			fclose($this->file);
		}
		// 输出结果
		parent::__destruct();
	}
}

set_time_limit(0);
$cc = new CUserQQUpload();

?>